﻿# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from thumbs import ImageWithThumbsField
import datetime

CATEGORIAS_CHOICES = (('1','Posicao 2'),('2','Posicao 3'),('3','Posicao 4(Esquerda)'),('4','Posicao 4(Direita)'),('5','Resumo da Semana'),('6','Ultimas (Esquerdo)'),('7','Ultimas (Direito)'))
CATEGORIA_EVENTO_CHOICES = (('1','Show'),('2','Palestra'),('3','Congresso'))
def content_image_name(instance, filename):
    return '/'.join(['arquivos', str(instance.nomeCategoria.slugcategoria), filename])

def download_image_name(instance, filename):
    return '/'.join(['arquivos/download', str(instance.nomeCantor.slugcantor), filename])

def destino_imagem_cantor(instance, filename):
    return '/'.join(['arquivos', str(instance.slugcantor), filename])

# Categoria de notícias
class Categoria(models.Model):
    nome = models.CharField(max_length=30)
    descricao = models.TextField(blank=True, null=True)
    cliques = models.IntegerField('Cliques', default=0, editable=False)
    slugcategoria = models.SlugField(max_length=100, blank=True, unique=True)
    class Meta:
        verbose_name_plural = 'Categoria de notícias'
    def __unicode__(self):
        return self.nome
    def get_absolute_url(self):
        return reverse('Scope.views.categoria', kwargs={'slugcategoria': self.slugcategoria})

# Base de notícias no banco de dados
class BaseNoticia(models.Model):
    publicar = models.BooleanField(default=True)
    manchete = models.BooleanField(default=False)
    titulo = models.CharField(max_length=100, unique=True)
    conteudo = models.TextField('Conteúdo')
    datacriacao = models.DateTimeField('Data', default=datetime.datetime.now)
    dataedicao = models.DateTimeField(auto_now=True)
    cliques = models.IntegerField('Cliques', default=0, editable=False)
    autor = models.ForeignKey(User, blank=True, null=True)
    class Meta:
        abstract = True


class Noticia(BaseNoticia):
    chamada = models.CharField(max_length=30)
    subtitulo = models.CharField(max_length=200)
    nomeCategoria = models.ForeignKey(Categoria)
    fonte = models.CharField(max_length=30, blank=True, null=True)
    imagem = ImageWithThumbsField('Imagem Destaque', upload_to=content_image_name, sizes=((800,600),(300,225)))
    slugnoticia = models.SlugField(max_length=200, blank=True, unique=True, editable=False)
    def __unicode__(self):
        return self.titulo
    def save(self):
        super(Noticia, self).save()
        if not self.nomeCategoria_id == 1:
            self.slugnoticia = '%s' % slugify(self.titulo)
        else:
            self.slugnoticia = '%i-%s' % (self.id, slugify(self.titulo))
        super(Noticia, self).save()
    def get_absolute_url(self):
        return reverse('Scope.views.noticiainterna', kwargs={'slugcategoria':self.nomeCategoria.slugcategoria,
                                                             'slugnoticia': self.slugnoticia
        })

class DataEvento(models.Model):
    eventoNoticia = models.ForeignKey(Noticia)
    dataevento = models.DateField('Data do evento', blank=True, null=True)
    local = models.CharField('Local', max_length=30)
    categoria = models.CharField('Categoria', max_length=2, choices=CATEGORIA_EVENTO_CHOICES, default=1)
    cidade = models.CharField('Cidade', max_length=20)
    organizacao = models.CharField('Organização', max_length=20)
    class Meta:
        verbose_name_plural = 'Se a notícia for um evento adicione uma data'

class VideoNoticia(models.Model):
    videoNoticia = models.ForeignKey(Noticia)
    usarVideo = models.BooleanField(default=False)
    video = models.CharField(max_length=15, help_text="fhbTBA64FkU")
    descricaovideo = models.CharField(max_length=500, blank=True, null=True)
    class Meta:
        verbose_name_plural = 'Adicionar vídeo do YouTube a notícia'

class Video(BaseNoticia):
    subtitulo = models.CharField(max_length=200)
    imagem = ImageWithThumbsField('Imagem', upload_to='arquivos/videos/', sizes=((800,600),(290,218)))
    url = models.CharField(max_length=15, help_text="fhbTBA64FkU")
    slugvideo = models.SlugField(max_length=200, blank=True, unique=True)
    def __unicode__(self):
        return self.titulo
    def get_absolute_url(self):
        return reverse('Scope.views.videointerna', kwargs={'slugvideo': self.slugvideo})

#Download
class Genero(models.Model):
    nome = models.CharField('Gênero musical', max_length=50, unique=True)
    cliques = models.IntegerField('Cliques', default=0, editable=False)
    sluggenero = models.SlugField(max_length=50, blank=True, unique=True)
    def __unicode__(self):
        return self.nome
    class Meta:
        verbose_name_plural = 'Gênero'

class Cantor(models.Model):
    publicar = models.BooleanField(default=True)
    manchete = models.BooleanField(default=False)
    nome = models.CharField('Nome do cantor', max_length=50, unique=True)
    nomeGenero = models.ForeignKey(Genero)
    descricao = models.TextField(blank=True, null=True)
    foto01 = ImageWithThumbsField('Foto', upload_to=destino_imagem_cantor, sizes=((800,600),(290,218)))
    foto02 = ImageWithThumbsField('Foto', upload_to=destino_imagem_cantor, sizes=((800,600),(290,218)))
    foto03 = ImageWithThumbsField('Foto', upload_to=destino_imagem_cantor, sizes=((800,600),(290,218)))
    siteoficial = models.URLField('Site Oficial', max_length=50, verify_exists=False)
    cliques = models.IntegerField('Cliques', default=0, editable=False)
    slugcantor = models.SlugField(max_length=50, blank=True, unique=True)
    def __unicode__(self):
        return self.nome
    def get_absolute_url(self):
        return reverse('Scope.views.cantor', kwargs={'slugdocantor': self.slugcantor})
    class Meta:
        verbose_name_plural = 'Cantores'

class Download(BaseNoticia):
    nomeCantor = models.ForeignKey(Cantor)
    album = models.CharField(max_length=100)
    ano = models.PositiveSmallIntegerField(max_length=4, default=2013)
    imagem = ImageWithThumbsField('Imagem Destaque', upload_to=download_image_name, sizes=((800,600),(300,225)), blank=True, null=True)
    slugdownload = models.SlugField(max_length=200, blank=True, unique=True)
    def __unicode__(self):
        return "%s - %s" % (self.nomeCantor.nome, self.album)
    def get_absolute_url(self):
        return reverse('Scope.views.downloadinterna', kwargs={'slugcantor':self.nomeCantor.slugcantor, 'slugdownload': self.slugdownload})

class LinkDownload(models.Model):
    link = models.URLField(max_length=30, verify_exists=False)
    linkDownload = models.ForeignKey(Download)
    def get_absolute_url(self):
        return reverse('Scope.views.downloadlink', kwargs={'iddownload':self.linkDownload_id})

#Letra
class Letra(BaseNoticia):
    nomeCantor = models.ForeignKey(Cantor)
    urlvideo = models.CharField(max_length=15, help_text="fhbTBA64FkU", blank=True, null=True)
    slugletra = models.SlugField(max_length=200, blank=True, unique=True)
    def get_absolute_url(self):
        return reverse('Scope.views.letrainterna', kwargs={ 'slugcategoria':self.nomeCantor.nome,'slugletra': self.slugletra,})


# SIGNALS
from django.db.models import signals
from django.template.defaultfilters import slugify

def download_pre_save(signal, instance, sender, **kwargs):
    if not instance.slugdownload:
            slug = slugify(instance.album)
            novaslug = slug
            contador = 0

            while  Download.objects.filter(slugdownload = novaslug).exclude(id=instance.id).count() > 0:
                contador += 1
                novaslug = '%s-%d'%(slug, contador)
            instance.slugdownload = novaslug
signals.pre_save.connect(download_pre_save, sender=Download)

def cantor_pre_save(signal, instance, sender, **kwargs):
    instance.slugcantor = slugify(instance.nome)

signals.pre_save.connect(cantor_pre_save, sender=Cantor)

def genero_pre_save(signal, instance, sender, **kwargs):
    instance.sluggenero = slugify(instance.nome)

signals.pre_save.connect(genero_pre_save, sender=Genero)

def video_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugvideo:
        slug = slugify(instance.titulo)
        novaslug = slug
        contador = 0

        while  Video.objects.filter(slugvideo = novaslug).exclude(id=instance.id).count() > 0:
            contador += 1
            novaslug = '%s-%d'%(slug, contador)
        instance.slugvideo = novaslug
signals.pre_save.connect(video_pre_save, sender=Video)

def categoria_pre_save(signal, instance, sender, **kwargs):
    instance.slugcategoria = slugify(instance.nome)

signals.pre_save.connect(categoria_pre_save, sender=Categoria)